<?php


namespace app\api\model;

use app\common\model\Lottery as LotteryModel;
use Think\Db;
use app\api\model\User as UserModel;
use app\api\model\UserCoupon as UserCouponModel;

class Lottery extends LotteryModel
{
    public function updateLotteryUser($transaction_id){
        //查询用户付款金额
        $payOrderInfo = Db::name('pay_order')->where(['transaction_id'=>$transaction_id])->find();
        if(!empty($payOrderInfo) && $payOrderInfo['pay_price'] >= 5) {
            $user = Db::name('user')->where('user_id',$payOrderInfo['user_id'])->find();
            $LotteryInfo = $this->getLotteryInfo($user);
            $lotteryUser = Db::name('lottery_user')->where('uid', $user['user_id'])->find();
            if(!empty($lotteryUser)) {
                $lotteryUser['cishu'] = $lotteryUser['cishu'] + 1;
                Db::name('lottery_user')->where('uid', $user['user_id'])->update($lotteryUser);
            }else{
                $data['uid'] = $user['user_id'];
                $data['cishu'] = 1;
                $data['type'] = 1;
                $data['add_date'] = date('Y-m-d H:i:s');
                Db::name('lottery_user')->insert($data);
            }
        }
    }
    public function getLotteryInfo($user = false){
        $this->where('lottery_status', '=', 10);
        $lotteryInfo = $this->find();
        if(empty($lotteryInfo)){
            return ['status'=>100,'msg'=>'活动已结束！'];
        }
        if(date('Y-m-d H:i:s') < $lotteryInfo['start_time']){
            return ['status'=>100,'msg'=>'活动还未开始！'];
        }
        if(date('Y-m-d H:i:s') > $lotteryInfo['end_time']){
            return ['status'=>100,'msg'=>'活动已结束！'];
        }
        //查询奖品
        $jiangpin = Db::name('lottery_jiangpin')->where(['lottery_id'=>$lotteryInfo['lottery_id']])->order('index asc')->select()->toArray();
        foreach ($jiangpin as $k=>$v){
            $jiangpins[$k]['coupon_id'] = 0;
            $jiangpins[$k]['coupon_name'] = '';
            if($v['types'] == 10){
                $name = '免单大奖';
            }elseif($v['types'] == 20){
                $name = $v['points'].'积分';
            }elseif($v['types'] == 30){
                $couponInfo = Db::name('coupon')->where('coupon_id',$v['coupon_id'])->find();
                $name = $couponInfo['name'];
                $jiangpins[$k]['coupon_id'] = $v['coupon_id'];
                $jiangpins[$k]['coupon_name'] = $couponInfo['name'];
            }elseif($v['types'] == 40){
                $name = $v['content'];
            }
            if($v['index'] == 0){
                $jiang = '一等奖';
            }elseif($v['index'] == 1){
                $jiang = '二等奖';
            }elseif($v['index'] == 2){
                $jiang = '三等奖';
            }elseif($v['index'] == 3){
                $jiang = '四等奖';
            }elseif($v['index'] == 4){
                $jiang = '五等奖';
            }
            $jiangpins[$k]['val'] = $jiang;
            $jiangpins[$k]['index'] = $v['index'];
            $jiangpins[$k]['name'] = $name;
            $jiangpins[$k]['id'] = $v['index']+1;
            $jiangpins[$k]['startAngle'] = $v['start_angle'];
            $jiangpins[$k]['endAngle'] = $v['end_angle'];
            $jiangpins[$k]['angle'] = $v['angle'];
            $jiangpins[$k]['v'] = $v['gailv'];
            $jiangpins[$k]['types'] = $v['types'];
            $jiangpins[$k]['points'] = $v['points'];
        }
        //查询用户抽奖次数
        $lotteryUser = Db::name('lottery_user')->where('uid',$user['user_id'])->find();
        if(empty($lotteryUser)){
            $lotteryInfo['cishu'] = 0;
        }else{
            $lotteryInfo['cishu'] = $lotteryUser['cishu'];
        }
        return ['status'=>200,'lotteryInfo'=>$lotteryInfo,'jiangpin'=>$jiangpins];
    }
    public function startUp($user = false){
        if(false == $user) return ['status'=>100,'msg'=>'请登陆！'];
        $lotteryUser = Db::name('lottery_user')->where('uid',$user['user_id'])->find();
        if(empty($lotteryUser) || $lotteryUser['cishu'] == 0){
            return ['status'=>100,'msg'=>'抽奖次数已用完！'];
        }
        $lotteryUser['cishu'] = $lotteryUser['cishu'] - 1;
        Db::name('lottery_user')->where('uid',$user['user_id'])->update($lotteryUser);
        $LotteryInfo = $this->getLotteryInfo($user);
        $prize_arr = $LotteryInfo['jiangpin'];
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }
        $rid = $this->get_rand($arr); //根据概率获取奖项id
//        $res['yes'] = $prize_arr[$rid-1]['name']; //中奖项
        $zhongJiangIndex = $prize_arr[$rid-1]['index']; //中奖项

        $log['status'] = 10;
        $log['duijiang_date'] = '';
        if($prize_arr[$rid-1]['types'] == 40){
            //实物
            $shiWuArr = explode('|',$prize_arr[$rid-1]['name']);
            $rands = mt_rand(0,count($shiWuArr));
            $zjName = $shiWuArr[$rands];
            $this->sendZhongJiangTmp($user,$zjName);
        }elseif($prize_arr[$rid-1]['types'] == 10){
            //免单
            $zjName = '免单大奖';
            $this->sendZhongJiangTmp($user,$zjName);
        }elseif($prize_arr[$rid-1]['types'] == 20){
            //积分
            $log['status'] = 20;
            $log['duijiang_date'] = date('Y-m-d H:i:s');
            $zjName = $prize_arr[$rid-1]['points'].'积分';

            $userModel = UserModel::detail($user['user_id']);
            //增加积分接口
            $describe = "抽奖奖励：{$zjName}";
            $userModel->setIncPoints($prize_arr[$rid-1]['points'], $describe);
            //发送模板消息
            $this->sendPointsTmp($user,$prize_arr[$rid-1]['points']);
        }elseif($prize_arr[$rid-1]['types'] == 30){
            //优惠券
            $log['status'] = 20;
            $log['duijiang_date'] = date('Y-m-d H:i:s');
            $coupon_id = $prize_arr[$rid-1]['coupon_id'];
            $zjName = $prize_arr[$rid-1]['coupon_name'];
            //增加用户优惠券接口
            $UserCouponModel = new UserCouponModel();
            $UserCouponModel->receive($user,$coupon_id);
            $this->sendZhongJiangTmp($user,$zjName,'pages/user/coupon/coupon');
        }
        if($prize_arr[$rid-1]['index'] == 0){
            $jiang = '一等奖';
        }elseif($prize_arr[$rid-1]['index'] == 1){
            $jiang = '二等奖';
        }elseif($prize_arr[$rid-1]['index'] == 2){
            $jiang = '三等奖';
        }elseif($prize_arr[$rid-1]['index'] == 3){
            $jiang = '四等奖';
        }elseif($prize_arr[$rid-1]['index'] == 4){
            $jiang = '五等奖';
        }
        $log['lottery_id'] = $LotteryInfo['lotteryInfo']['lottery_id'];
        $log['uid'] = $user['user_id'];
        $log['jiangxiang'] = $jiang;
        $log['jiangpin'] = $zjName;
        $log['add_date'] = date('Y-m-d H:i:s');
        Db::name('lottery_user_zhongjiang_log')->insert($log);
        return ['status'=>200,'zhongJiangIndex'=>$zhongJiangIndex,'zjName'=>$zjName,'jiang'=>$jiang];
    }

    /*
     * 经典的概率算法，
     * $proArr是一个预先设置的数组，
     * 假设数组为：array(100,200,300，400)，
     * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内，
     * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
     * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
     * 这样 筛选到最终，总会有一个数满足要求。
     * 就相当于去一个箱子里摸东西，
     * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
     * 这个算法简单，而且效率非常高，
     * 这个算法在大数据量的项目中效率非常棒。
     */
    function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
    /**
     * 发送中奖到账模板消息
     * @param $userInfo
     */
    public function sendZhongJiangTmp($userInfo, $zjName,$pagepath = 'pages/index/index'){

        $template_id = '-QvhdbnFh3Xcw_e2VExcyScM6-_hIOESunqn6s-GUDQ';
        $url = '';
        $openid = $userInfo['openid'];
        $appid = 'wxca5a1f0a213b34b7';

        $datas = [
            'first' => ['value' => "恭喜你获得奖品！\n"],
            'keyword1' => ['value' => $zjName],
            'keyword2' => ['value' => date('Y年m月d日 H时i分s秒')],
            'remark' => ['value' => "\n点击查看账户详情。" ,'color' => '#ff0000']
        ];
        sendTmp($template_id, $openid, $datas,$appid, $pagepath, $url);
    }
    /**
     * 发送积分到账模板消息
     * @param $userInfo
     */
    public function sendPointsTmp($userInfo, $gift_money){

        $template_id = 'gIQnIDPmH2o1761I1xUyj8XowFDPqE5evdtXbs5rUZw';
        $url = '';
        $openid = $userInfo['openid'];
        $appid = 'wxca5a1f0a213b34b7';
        $pagepath = 'pages/index/index';

        $datas = [
            'first' => ['value' => "尊敬的客户您好，您的积分已经发送到您的宜品购账户，请查收！\n"],
            'keyword1' => ['value' => $userInfo['nickName']],
            'keyword2' => ['value' => date('Y年m月d日 H时i分s秒')],
            'keyword3' => ['value' => '大转盘抽奖奖励'],
            'keyword4' => ['value' => $gift_money.'积分'],
            'keyword5' => ['value' => $userInfo['points']+$gift_money.'积分'],
            'remark' => ['value' => "\n点击查看账户详情。\n您本次获得的积分可在宜品购平台直接抵现" ,'color' => '#ff0000']
        ];
        sendTmp($template_id, $openid, $datas,$appid, $pagepath, $url);
    }
}